/*
 * SocketConnection.cpp
 *
 *  Created on: 2012-2-6
 *      Author: chenjialiang
 */

#include "SocketConnection.h"
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

namespace Zha
{

SocketConnection::SocketConnection()
{
	m_bindAddr = "";
	m_bindPort = 12345;
	m_block = false;
	m_reusePort = false;
	m_socket = 0;
}

SocketConnection::~SocketConnection()
{
	// TODO Auto-generated destructor stub
}

int SocketConnection::Init()
{
	sockaddr_in my_addr; /* 本机地址信息 */

	if ((m_socket = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		Log("socket create error, %s, %s！", __FILE__, __LINE__);
		return 1;
	}

	my_addr.sin_family=AF_INET;
	my_addr.sin_port=htons(m_bindPort);

	if (m_bindAddr.length() == 0)
	{
		my_addr.sin_addr.s_addr = INADDR_ANY;
		Log("Bind address to localhost");
	}

	if (m_reusePort)
	{/*
		int optval = 1;
		int optlen = sizeof(optval);
		int tval;
		int tlen = sizeof(tval);

		if (setsockopt(m_socket , SOL_SOCKET, SO_REUSEPORT, ( char *)&optval, optlen) != 0)
		{
			printf("%m\n");
		}

		printf("reusePort:%d\n", tval);
		*/
	}

	bzero(&(my_addr.sin_zero),8);

	if (bind(m_socket, (sockaddr *)&my_addr, sizeof(sockaddr))  == -1)
	{
		Log("bind error, %s, %s！", __FILE__, __LINE__);
		return 2;
	}

	if (listen(m_socket, 10) == -1)
	{
		Log("listen error, %s, %s", __FILE__, __LINE__);
		return 3;
	}

	Log("Listen to port:%d", m_bindPort);
	return 0;
}

int SocketConnection::Read(int clientSocket, char* buf, int size)
{
	if (clientSocket <= 0)
	{
		return 0;
	}

	return recv(clientSocket, buf, size, 0);
}

int SocketConnection::Accept()
{
	sockaddr_in client_addr;
	socklen_t sin_size=sizeof(sockaddr_in);
	int clientSocket = -1;

	if((clientSocket=accept(m_socket,(sockaddr *)&client_addr,&sin_size)) == -1)
	{
		Log("accept fail, %s, %s！", __FILE__, __LINE__);
		return -1;
	}

	return clientSocket;
}

}


